package com.miaoshare.core.utils.imageLoad;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.widget.ImageView;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.load.resource.bitmap.VideoDecoder;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener;
import com.miaoshare.core.R;
import com.miaoshare.core.utils.DimenUtil;
import com.miaoshare.core.utils.GlideEngine;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;

import jp.wasabeef.glide.transformations.BlurTransformation;

/**
 * 图片加载工具类
 * Created by zxs
 * on 2022/2/10
 */
@SuppressWarnings({"unused"})
public class ImageManager {
    private Context mContext;
    public static final String ANDROID_RESOURCE = "android.resource://";
    public static final String FOREWARD_SLASH = "/";
    public RequestOptions head_options;

    private static final Object LOCK = new Object();
    @SuppressLint("StaticFieldLeak")
    private static ImageManager instance;
    /*默认图片，根据业务自行替换*/
    public static int[] defImg = {R.drawable.ic_launcher_background};

    public static ImageManager get() {
        synchronized (LOCK) {
            if (instance == null) {
                instance = new ImageManager();
            }
            return instance;
        }
    }

    public void init(Context context) {
        mContext = context;
        //头像
        head_options = new RequestOptions()
                .centerCrop()
                .error(defImg[0])
                .priority(Priority.HIGH);
    }

    public static void recycle() {
        synchronized (LOCK) {
            if (instance != null) {
                instance.mContext = null;
                instance = null;
            }
        }
    }

    private ImageManager() {
    }

    // 将资源ID转为Uri
    public Uri resourceIdToUri(int resourceId) {
        return Uri.parse(ANDROID_RESOURCE + mContext.getPackageName() + FOREWARD_SLASH + resourceId);
    }

    /**
     * 加载视频第一针
     *
     * @param uri
     * @param imageView
     * @param frameTimeMicros
     */
    public void loadVideoScreenshot(String uri, ImageView imageView, long frameTimeMicros) {
        RequestOptions requestOptions = RequestOptions.frameOf(frameTimeMicros);
        requestOptions.set(VideoDecoder.FRAME_OPTION, MediaMetadataRetriever.OPTION_CLOSEST);
        requestOptions.transform(new BitmapTransformation() {
            @Override
            protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
                return toTransform;
            }

            @Override
            public void updateDiskCacheKey(MessageDigest messageDigest) {
                try {
                    messageDigest.update((mContext.getPackageName() + "RotateTransform").getBytes("utf-8"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        Glide.with(mContext).load(uri).apply(requestOptions).into(imageView);
    }

    public void loadVideoScreenshot(String url, ImageView imageView,
                                    @DrawableRes int defaultImage, int radiusInPx) {
        Glide.with(mContext)
                .load(url)
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .apply(new RequestOptions()
                        .transform(new GlideSquareRoundTransform(mContext, radiusInPx))
                        .error(defaultImage)
                        .priority(Priority.HIGH))
                .into(imageView);
    }

    public Bitmap getBitmapFormUrl(String url) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            if (Build.VERSION.SDK_INT >= 20) {
                retriever.setDataSource(url, new HashMap<String, String>());
            } else {
                retriever.setDataSource(url);
            }
            /*getFrameAtTime()--->在setDataSource()之后调用此方法。 如果可能，该方法在任何时间位置找到代表性的帧，         并将其作为位图返回。这对于生成输入数据源的缩略图很有用。**/
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    /***
     * 加载网络图片 原图
     * @param url   加载地址
     * @param imageView  图片控件
     */
    public void loadUrlImage(String url, ImageView imageView) {
        Glide.with(mContext)
                .load(url)
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .apply(new RequestOptions()
                        .error(defImg[0])
                        .priority(Priority.HIGH))
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        imageView.setImageDrawable(resource);
                        if (resource instanceof GifDrawable) {
                            GifDrawable gifDrawable = (GifDrawable) resource;
                            gifDrawable.stop();
                        }
                    }
                });
    }

    /***
     * 加载网络图片 原图
     * @param url   加载地址
     * @param imageView  图片控件
     * @param listener  加载回调
     */
    public void loadUrlImage(String url, ImageView imageView, RequestListener<Drawable> listener) {
        Glide.with(mContext)
                .load(url)
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .apply(new RequestOptions()
                        .error(defImg[0])
                        .priority(Priority.HIGH))
                .listener(listener)
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        imageView.setImageDrawable(resource);
                        if (resource instanceof GifDrawable) {
                            GifDrawable gifDrawable = (GifDrawable) resource;
                            gifDrawable.stop();
                        }
                    }
                });
    }

    /***
     * 加载网络图片 处理后
     * @param url   加载地址
     * @param imageView  图片控件
     * @param h    图片高度
     */
    public void loadUrlImage(String url, ImageView imageView, int h) {
        Glide.with(mContext)
                .load(String.format("%1$s?x-oss-process=image/resize,h_%2$s", url, h))
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .apply(new RequestOptions()
                        .placeholder(defImg[0])
                        .error(defImg[0])
                        .priority(Priority.HIGH))
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        imageView.setImageDrawable(resource);
                        if (resource instanceof GifDrawable) {
                            GifDrawable gifDrawable = (GifDrawable) resource;
                            gifDrawable.stop();
                        }
                    }
                });
    }

    public void loadUrlVideo(String url, ImageView imageView) {
        Glide.with(mContext)
                .load(url)
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .apply(new RequestOptions()
                        .placeholder(defImg[0])
                        .error(defImg[0])
                        .priority(Priority.HIGH))
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        imageView.setImageDrawable(resource);
                        if (resource instanceof GifDrawable) {
                            GifDrawable gifDrawable = (GifDrawable) resource;
                            gifDrawable.stop();
                        }
                    }
                });
    }

    /***
     * 加载网络图片 处理后
     * @param url   加载地址
     * @param imageView  图片控件
     * @param w    图片宽度
     */
    public void loadUrlImageWidth(String url, ImageView imageView, int w) {
        Glide.with(mContext)
                .load(String.format("%1$s?x-oss-process=image/resize,w_%2$s", url, w))
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .apply(new RequestOptions()
                        .placeholder(defImg[0])
                        .error(defImg[0])
                        .priority(Priority.HIGH))
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        imageView.setImageDrawable(resource);
                        if (resource instanceof GifDrawable) {
                            GifDrawable gifDrawable = (GifDrawable) resource;
                            gifDrawable.stop();
                        }
                    }
                });
    }

    /***
     * 加载网络图片-正方形
     * @param url   加载地址
     * @param imageView  图片控件
     * @param defaultImage  默认图片
     */
    public void loadSquareUrlImage(String url, ImageView imageView, int imageLength, @DrawableRes int defaultImage) {
        Glide.with(mContext)
                .load(String.format("%1$s?x-oss-process=image/resize,m_fill,w_%2$s,h_%3$s", url, imageLength, imageLength))
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .apply(new RequestOptions()
                        .error(defaultImage)
                        .priority(Priority.HIGH))
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        imageView.setImageDrawable(resource);
                        if (resource instanceof GifDrawable) {
                            GifDrawable gifDrawable = (GifDrawable) resource;
                            gifDrawable.stop();
                        }
                    }
                });
    }


    /***
     * 加载网络图片-正方形-圆角
     * @param url   加载地址
     * @param imageView  图片控件
     * @param defaultImage  默认图片
     */
    public void loadSquareUrlImage(String url, ImageView imageView, int imageLength, @DrawableRes int defaultImage, int radiusInPx) {
        Glide.with(mContext)
                .load(String.format("%1$s?x-oss-process=image/resize,m_fill,w_%2$s,h_%3$s", url, imageLength, imageLength))
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .apply(new RequestOptions()
                        .transform(new GlideRoundTransform(mContext, radiusInPx))
                        .error(defaultImage)
                        .priority(Priority.HIGH))
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        imageView.setImageDrawable(resource);
                        if (resource instanceof GifDrawable) {
                            GifDrawable gifDrawable = (GifDrawable) resource;
                            gifDrawable.stop();
                        }
                    }
                });
    }

    /***
     * 加载本地图片-正方形-圆角
     * @param path   加载地址
     * @param imageView  图片控件
     * @param defaultImage  默认图片
     */
    public void loadSquareLocalImage(String path, ImageView imageView,
                                     @DrawableRes int defaultImage) {
        Glide.with(mContext)
                .load("file://" + path)
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .apply(new RequestOptions()
                        .error(defaultImage)
                        .priority(Priority.HIGH))
                .into(imageView);
    }

    /***
     * 加载本地图片-正方形-圆角
     * @param path   加载地址
     * @param imageView  图片控件
     * @param defaultImage  默认图片
     */
    public void loadSquareLocalImage(String path, ImageView imageView,
                                     @DrawableRes int defaultImage, int radiusInPx) {
        Glide.with(mContext)
                .load("file://" + path)
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .apply(new RequestOptions()
                        .transform(new GlideSquareRoundTransform(mContext, radiusInPx))
                        .error(defaultImage)
                        .priority(Priority.HIGH))
                .into(imageView);
    }

    /**
     * 加载网络图片-圆形
     *
     * @param url       加载地址
     * @param imageView 图片控件
     */
    public void loadCircleImage(String url, ImageView imageView) {
        if (TextUtils.isEmpty(url)) {
            imageView.setImageResource(defImg[0]);
            return;
        }
        Glide.with(mContext)
                // 如果原图是1000*1000，需要的是100*100，则该操作只会得到原图最中心的部分，所以用方形操作，再用glide自带的裁剪功能
//                .load(String.format("%1$s?x-oss-process=image/circle,r_%2$s/format,png", url, d/2))
                .load(url)
                .apply(head_options)
                .apply(RequestOptions.circleCropTransform())
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .into(imageView);
    }

    /**
     * 加载网络图片-圆形
     *
     * @param url       加载地址
     * @param imageView 图片控件
     * @param d         直径
     */
    public void loadCircleImage(String url, ImageView imageView, int d) {
        if (TextUtils.isEmpty(url)) {
            imageView.setImageResource(defImg[0]);
            return;
        }
        Glide.with(mContext)
                // 如果原图是1000*1000，需要的是100*100，则该操作只会得到原图最中心的部分，所以用方形操作，再用glide自带的裁剪功能
//                .load(String.format("%1$s?x-oss-process=image/circle,r_%2$s/format,png", url, d/2))
                .load(url.startsWith("http://sikuyipingtai") ?
                        String.format("%1$s?x-oss-process=image/resize,m_fill,w_%2$s,h_%3$s", url, d, d) : url)
                .apply(head_options)
                .apply(RequestOptions.circleCropTransform())
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .into(imageView);
    }


    // 加载本地圆型图片
    public void loadCircleLocalImage(String path, ImageView imageView) {
        Glide.with(mContext)
                .load("file://" + path)
                .apply(head_options)
                .apply(RequestOptions.circleCropTransform())
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .into(imageView);
    }

    /***
     * 加载本地图片
     * @param path   加载地址
     * @param imageView  图片控件
     */
    public void loadLocalImage(String path, ImageView imageView) {
        Glide.with(mContext)
                .load("file://" + path)
                .apply(new RequestOptions()
                        .error(defImg[0])
                        .priority(Priority.HIGH))
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .into(imageView);
    }

    /***
     * 加载本地图片
     * @param path   加载地址
     * @param imageView  图片控件
     * @param listener  加载回调
     */
    public void loadLocalImage(String path, ImageView imageView, RequestListener<Drawable> listener) {
        Glide.with(mContext)
                .load("file://" + path)
                .apply(new RequestOptions()
                        .error(defImg[0])
                        .priority(Priority.HIGH))
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .listener(listener)
                .into(imageView);
    }

    // 加载本地圆角图片
    public void loadLocalImage(String path, ImageView imageView, int radiusInPx) {
        Glide.with(mContext)
                .load("file://" + path)
                .apply(new RequestOptions()
                        .transform(new GlideRoundTransform(mContext, radiusInPx))
                        .error(defImg[0])
                        .priority(Priority.HIGH))
                .transition(new DrawableTransitionOptions().crossFade(2000))
                .into(imageView);
    }

    /**
     * 加载网络图片-高斯模糊圆形
     *
     * @param url        加载地址
     * @param imageView  图片控件
     * @param d          直径
     * @param BlurRadius 模糊度 圆角和高斯模糊,设置模糊度(在0.0到25.0之间)，默认”25";"4":图片缩放比例,默认“1”
     */
    public void loadCircleBigmapBlurImage(String url, ImageView imageView, int d, int BlurRadius) {
        if (TextUtils.isEmpty(url)) {
            int resourceId = defImg[0];
            Glide.with(mContext).asBitmap()
                    .load(resourceId)
                    .apply(new RequestOptions()
                            .fitCenter().placeholder(defImg[0])
                            .bitmapTransform(new MultiTransformation<>(new BlurTransformation(BlurRadius, 1)
                                    , new RoundedCorners(50)))
                            .override(100, 100)
                            .error(R.drawable.ic_launcher_background)
                            .priority(Priority.HIGH))
                    .into(imageView);
            return;
        }
        Glide.with(mContext).asBitmap()
                // 可替换自己的域名
                .load(url.startsWith("http://sikuyipingtai") ?
                        String.format("%1$s?x-oss-process=image/resize,m_fill,w_%2$s,h_%3$s", url, d, d) : url)
                .apply(new RequestOptions()
                        .fitCenter().placeholder(defImg[0])
                        .bitmapTransform(new MultiTransformation<>(new BlurTransformation(BlurRadius, 1)
                                , new RoundedCorners(50)))
                        .override(100, 100)
                        .error(defImg[0])
                        .priority(Priority.HIGH))
                .into(imageView);
    }

    /**
     * 将文字绘制成图
     *
     * @param bitmapColor  圆的颜色
     * @param backColor    图片背景颜色
     * @param txtColor     文字的颜色
     * @param text         文字
     * @param circleWidth  图片宽度
     * @param circleHeight 图片高度
     * @return
     */

    public Bitmap drawImg(int bitmapColor, int backColor, int txtColor, String text, int circleWidth, int circleHeight) {
        if (circleHeight <= 0) { //做判断，如果传入的高度为0，则默认为60
            circleHeight = 60;
        }
        if (circleWidth <= 0) { //做判断，如果传入的宽度为0，则默认为60
            circleWidth = 60;
        }
        if (text == null) { //如果传入的文字为空，则设置为空格
            text = " ";
        }
        Bitmap bitmap = Bitmap.createBitmap(circleWidth, circleHeight, Bitmap.Config.ARGB_8888);//设置生成的bitmap为高清
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(bitmapColor);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(backColor);
        int raduis = Math.min(bitmap.getWidth() / 2, bitmap.getHeight() / 2);
        canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, raduis, paint);
        TextPaint txtPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        txtPaint.setTextSize(DimenUtil.sp2px(mContext, 12));
        txtPaint.setColor(txtColor);
        txtPaint.setStrokeWidth(10);
//1.字符串子资源
//2 .画笔对象
//3.layout的宽度，字符串超出宽度时自动换行。
//4.layout的样式，有ALIGN_CENTER， ALIGN_NORMAL， ALIGN_OPPOSITE  三种。
//5.相对行间距，相对字体大小，1.5f表示行间距为1.5倍的字体高度。
//6.相对行间距，0表示0个像素。
        StaticLayout sl = new StaticLayout(text, txtPaint, bitmap.getWidth() - 2, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
        float txtWid = txtPaint.measureText(text);
//        if (text.length() == 1) {
//            canvas.drawText(text, (bitmap.getWidth() - txtWid) / 2, bitmap.getHeight() / 2 + bitmap.getHeight() / 3 / 2, txtPaint);
//        } else {
//            canvas.drawText(text, (bitmap.getWidth() - txtWid) / text.length(), bitmap.getHeight() / 2 + bitmap.getHeight() / 3 / 2, txtPaint);
//        }
        canvas.save();
        canvas.restore();
        //文字的坐标
        if (text.length() > 2) {
            canvas.translate(2, 9);
        } else {
            canvas.translate(2, 18);
        }
        sl.draw(canvas);
        return bitmap;

    }

    /**
     * 预览图片
     * https://github.com/LuckSiege/PictureSelector
     */
    public void previewImage(Activity activity, int position, ArrayList<LocalMedia> localMediaList) {
        PictureSelector.create(activity)
                .openPreview()
                .setImageEngine(GlideEngine.createGlideEngine())
                .setExternalPreviewEventListener(new OnExternalPreviewEventListener() {
                    @Override
                    public void onPreviewDelete(int position) {

                    }

                    @Override
                    public boolean onLongPressDownload(LocalMedia media) {
                        return false;
                    }
                }).startActivityPreview(position, true, localMediaList);

    }


}
